package middleware

import (
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"go-papers/tools/app"
	"go-papers/tools/config"

	mycasbin "go-papers/pkg/casbin"
	"go-papers/pkg/jwtauth"
	_ "go-papers/pkg/jwtauth"
)

//权限检查中间件
func AuthCheckRole() gin.HandlerFunc {
	return func(c *gin.Context) {
		data, _ := c.Get("JWT_PAYLOAD")

		//qa 不言
		if config.GConfig.Config.Model != "local" {
			c.Next()
			return
		}

		v := data.(jwtauth.MapClaims)
		e, err := mycasbin.Casbin()
		if err != nil {
			log.Println("------verify  Casbin----------", v["rolekey"], err)
			//c.Next()

			c.JSON(http.StatusOK, gin.H{
				"code":    403,
				"message": "对不起，您没有该接口访问权限" + err.Error(),
				"data":    nil,
			})
			c.Abort()
			return
		}
		if err != nil {
			app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
			return
		}

		//检查权限
		res, err := e.Enforce(v["rolekey"], c.Request.URL.Path, c.Request.Method)
		log.Println("------verify  authority----------", v["rolekey"], c.Request.URL.Path, c.Request.Method, res)
		if c.Request.URL.Path == "/backend/rolemenu" {
			res = true
		}

		if err != nil && !res {
			if err != nil {
				app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
				return
			}

		}

		if res {
			c.Next()
		} else {
			c.JSON(http.StatusOK, gin.H{
				"code":    403,
				"message": "对不起，您没有该接口访问权限，请联系管理员",
				"data":    nil,
			})
			c.Abort()
			return
		}
	}
}
